<template>
  <div>
    <el-form :model="condition" size="small" :inline="true">
      <el-form-item label="姓名">
        <el-input v-model="condition.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="condition.sex" placeholder="请选择性别" clearable>
          <el-option v-for="(s,index) in sexArr" :key="index" :label="s" :value="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        <el-button icon="el-icon-refresh-left" @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="height: 34px">
      <el-pagination background align="right" v-show="total > 0"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="pageSizes"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next"
                     :total="total">
      </el-pagination>
    </div>
    <!-- el-table的data属性就是用来绑定这个表格显示的数据 -->
    <el-table :data="users" height="250" style="width: 100%">
      <!-- el-table-column表示表格的每一列信息 label属性表示表头的名称
         prop表示绑定的字段名 width属性表示这一列显示的宽度-->
      <el-table-column prop="username" label="账号"/>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="sex" label="性别">
        <template slot-scope="scope">
          <span v-if="scope.row.sex === 0">男</span>
          <span v-else-if="scope.row.sex === 1">女</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄"/>
      <el-table-column prop="phone" label="联系电话"/>
      <el-table-column prop="email" label="联系邮箱"/>
      <el-table-column prop="state" label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.state === 0">冻结</span>
          <span v-else>正常</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showUserDialog(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.state === 1" type="text" @click="changeFrozenState(scope.row.username, 1, 0)">冻结</el-button>
          <el-button v-else type="text" @click="changeFrozenState(scope.row.username,0, 1)">解冻</el-button>
          <el-button type="text" @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="编辑用户信息" :visible.sync="userDialog.visible" width="50%">
      <el-form :model="userDialog.editUser" :rules="userDialog.userRules" ref="userForm" :inline="true">
        <el-form-item label="账号">
          <el-input v-model="userDialog.editUser.username" readonly/>
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input v-model="userDialog.editUser.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-select v-model="userDialog.editUser.sex" placeholder="请选择性别" clearable>
            <el-option v-for="(s,index) in sexArr" :key="index" :label="s" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="age" label="年龄">
          <el-input v-model="userDialog.editUser.age" placeholder="请输入年龄" clearable />
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="userDialog.editUser.phone" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item prop="email" label="联系邮箱">
          <el-input v-model="userDialog.editUser.email" placeholder="请输入联系邮箱" clearable />
        </el-form-item>
        <el-form-item prop="entryTime" label="入职时间">
          <el-date-picker v-model="userDialog.editUser.entryTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" clearable/>
        </el-form-item>
        <el-form-item prop="leaveTime" label="离职时间">
          <el-date-picker v-model="userDialog.editUser.leaveTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" clearable/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="save">保 存</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data(){
    return {
      condition: {
        name: '',
        sex: ''
      },
      sexArr: ['男', '女', '其他'],
      users: [],
      currentPage: 1, //分页的默认页码应该是第一页
      pageSizes: [50, 100, 150, 200, 400], //可选的每页显示条数
      pageSize: 50, //每页显示条数
      total: 0, //查询的总条数，默认值为0，查询之后才会赋值
      userDialog: {
        visible: false,
        editUser: {
          username: '',
          name: '',
          sex: '',
          age: '',
          phone: '',
          email: '',
          entryTime: '',
          leaveTime: ''
        },
        userRules: {
          username: [
            {required: true, message: '账号不能为空', trigger: ['blur', 'change']}
          ],
          name: [
            {required: true, message: '姓名不能为空', trigger: ['blur', 'change']}
          ],
          sex: [
            {required: true, message: '性别不能为空', trigger: ['blur', 'change']}
          ]
        }
      }
    }
  },
  methods: {
    handleSizeChange(val){//这个函数是用来监听每页显示条数的变更
      this.currentPage = 1
      this.pageSize = val
      this.search()
    },
    handleCurrentChange(val){//这个函数是用来监听当前页码变化
      this.currentPage = val
      this.search()
    },
    search(){
      this.doGet('/user', {
        name: this.condition.name,
        sex: this.condition.sex,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }, resp => {
        this.users = resp.records
        this.total = resp.total
      })
    },
    showUserDialog(user){
      //首先获取user对象的属性集合，然后遍历这个集合，将每一个属性值拷贝到editUser对象中
      Object.keys(user).forEach(key => this.userDialog.editUser[key] = user[key])
      this.userDialog.visible = true
    },
    closeDialog(){
      this.userDialog.visible = false
      this.userDialog.editUser = {
        username: '',
        name: '',
        sex: '',
        age: '',
        phone: '',
        email: '',
        entryTime: '',
        leaveTime: ''
      }
      //重置所有的表单验证，这样可以清除提示信息
      this.$refs['userForm'].resetFields();
    },
    save(){
      this.$refs['userForm'].validate(valid => {
        if(valid){
          //这里就可以提交信息去后台服务器保存数据
          this.doPut('/user', this.userDialog.editUser, resp => {
            if(resp){
               this.$message.success("保存成功")
               this.closeDialog()
               this.search()
            } else {
               this.$message.error("保存失败")
            }
          })
        } else {
          return false
        }
      })
    },
    deleteUser(user){
      this.showConfirm(`确定要删除用户${user.username}吗?`, () => {
        //点击确定按钮后才会执行删除动作
        this.doDelete(`/user/${user.username}`, {}, resp  => {
           if(resp){
             this.$message.success("删除成功")
             this.search()
           } else {
             this.$message.error("删除失败")
           }
        })
      })
    },
    reset(){
      this. condition = {
        name: '',
        sex: ''
      }
      this.search()
    },
    changeFrozenState(username, oldState, newState){
      this.doPut('/user/state', {
        username: username,
        oldState: oldState,
        newState: newState
      }, resp => {
        if(resp){
          this.$message.success(`${newState === 0 ? '冻结': '解冻'}成功`)
          this.search()
        } else {
          this.$message.error(`${newState === 0 ? '冻结': '解冻'}失败`)
        }
      })
    }
  },
  mounted() { //这个函数是一个钩子函数，有vue自动调用，在页面完成挂载之后就会调用这个函数
    this.search()
  }
}
</script>

<style scoped>

</style>
